package com.yami.shop.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yami.shop.bean.enums.EsOperationType;
import com.yami.shop.bean.event.EsProductUpdateEvent;
import com.yami.shop.bean.event.ProdStockChangeStatusEvent;
import com.yami.shop.bean.model.ProdExtension;
import com.yami.shop.bean.model.Product;
import com.yami.shop.service.ProdExtensionService;
import com.yami.shop.service.ProdParameterService;
import com.yami.shop.service.ProductService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 功能描述: 活动商品修改状态
 * @Author: LSR
 * @Date: 2023/4/24 18:41
 */
@Component
@Log4j2
public class ProdStatusListener {

    @Autowired
    private ProductService productService;

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    private ProdExtensionService prodExtensionService;
    @Autowired
    private ProdParameterService prodParameterService;

    @EventListener(ProdStockChangeStatusEvent.class)
    public void updateStatus(ProdStockChangeStatusEvent event){
        // 查询商品是否有库存
        ProdExtension byProdId = prodExtensionService.getOne(new LambdaQueryWrapper<ProdExtension>().eq(ProdExtension::getProdId, event.getProdId()));
        log.info("商品库存为0修改为已售罄================进入");
        if(byProdId.getLockStock() == 0 && byProdId.getStock() == 0){
            // 实际库存 与 锁定库存为0 时 修改商品状态为 售罄
            LambdaUpdateWrapper<Product> productUpdateWrapper = new LambdaUpdateWrapper<>();
            productUpdateWrapper.eq(Product::getProdId,event.getProdId());
            productUpdateWrapper.set(Product::getStatus,4);
            productService.update(productUpdateWrapper);
            log.info("商品库存为0修改为已售罄================修改结束");
            removeCache(event.getProdId());
        }
    }

    // 清除缓存 修改ES
    public void removeCache(Long prodId){
        productService.removeProdCacheByProdId(prodId);
        prodParameterService.removeCacheByProdId(prodId);
        eventPublisher.publishEvent(new EsProductUpdateEvent(prodId, null, EsOperationType.UPDATE));
    }
}
